#include "Buzzer.h"
#include "Delay.h"

// 频率数组
static const u16 hz_table[] = {1800, 1300, 800, 400};

// GPIO配置
static void gpio_config(void) {
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.Pin  = GPIO_Pin_0;
    GPIO_InitStructure.Mode = GPIO_OUT_PP;
    GPIO_Inilize(GPIO_P0, &GPIO_InitStructure);
}

// PWM配置
static void pwm_config(u16 hz) {
    PWMx_InitDefine init;
    u16 Period = MAIN_Fosc / hz - 1;

    init.PWM_Mode = CCMRn_PWM_MODE1;
    init.PWM_Period = Period;
    init.PWM_Duty = Period * 0.5;
    init.PWM_DeadTime = 0;
    init.PWM_EnoSelect = ENO5P;
    init.PWM_CEN_Enable = ENABLE;
    init.PWM_MainOutEnable = ENABLE;

    PWM_Configuration(PWM5, &init);
    PWM_Configuration(PWMB, &init);
    PWM5_SW(PWM5_SW_P00);
}

// 停止PWM
static void pwm_stop(void) {
    PWM_Configuration(PWMB, NULL);
}

// 初始化声音模块
void sound_init() {
    EAXSFR();
    gpio_config();
}

// 播放指定模式的声音
void sound_play(sound_mode_t mode) {
    u8 i;
    
    switch(mode) {
        case SOUND_SET_SUCCESS:
            for(i = 0; i < 3; i++) {
                pwm_config(hz_table[1]);
                delay_ms(150);
                pwm_config(hz_table[0]);
                delay_ms(150);
                pwm_stop();
                delay_ms(100);
            }
            break;
            
        case SOUND_SET_FAIL:
            for(i = 0; i < 3; i++) {
                pwm_config(hz_table[3]);
                delay_ms(200);
                pwm_config(hz_table[2]);
                delay_ms(200);
                pwm_stop();
                delay_ms(150);
            }
            break;
            
        case SOUND_CLOCKIN_SUCCESS:
            for(i = 0; i < 3; i++) {
                pwm_config(hz_table[0]);
                delay_ms(100);
                pwm_stop();
                delay_ms(50);
            }
            break;
            
        case SOUND_CLOCKIN_FAIL:
            for(i = 0; i < 3; i++) {
                pwm_config(hz_table[3]);
                delay_ms(300);
                pwm_stop();
            }
            break;
            
        case SOUND_NONE:
        default:
            pwm_stop();
            break;
    }
}

// 停止声音
void sound_stop() {
    pwm_stop();
}